<?php
namespace app\common\libs;

use app\api\cache\KeysUtil;
use app\api\cache\RedisCache;

class Jwt
{
    //头部
    private static $header = [
        'alg' => 'HS256', //生成signature的算法
        'typ' => 'JWT', //类型
    ];

    //使用HMAC生成信息摘要时所使用的密钥
    private static $key = 'qmx%&*%¥%&';

    /**
     * 获取jwt token
     * @param array $payload jwt载荷   格式如下非必须
     * @return bool|string
     */
    public static function getToken(array $payload)
    {
        if (is_array($payload)) {
            $base64header  = self::base64UrlEncode(json_encode(self::$header, JSON_UNESCAPED_UNICODE));
            $base64payload = self::base64UrlEncode(json_encode($payload, JSON_UNESCAPED_UNICODE));
            $token         = $base64header . '.' . $base64payload . '.' . self::signature($base64header . '.' . $base64payload, self::$key,
                self::$header['alg']);
            return $token;
        } else {
            return false;
        }
    }

    /**
     * 验证token是否有效,默认验证exp,nbf,iat时间
     * @param string $token 需要验证的token
     * @return bool|string
     */
    public static function verifyToken($token)
    {
        $tokens = explode('.', $token);
        if (count($tokens) != 3) {
            return false;
        }

        list($base64header, $base64payload, $sign) = $tokens;

        //获取jwt算法
        $base64decodeheader = json_decode(self::base64UrlDecode($base64header), JSON_OBJECT_AS_ARRAY);
        if (empty($base64decodeheader['alg'])) {
            return false;
        }

        //签名验证
        if (self::signature($base64header . '.' . $base64payload, self::$key, $base64decodeheader['alg']) !== $sign) {
            return false;
        }

        $payload = json_decode(self::base64UrlDecode($base64payload), JSON_OBJECT_AS_ARRAY);

        //签发时间大于当前服务器时间验证失败
        // if (isset($payload['iat']) && $payload['iat'] > time()) {
        //     return false;
        // }

        // //过期时间小宇当前服务器时间验证失败
        // if (isset($payload['exp']) && $payload['exp'] < time()) {
        //     return false;
        // }

        // //该nbf时间之前不接收处理该Token
        // if (isset($payload['nbf']) && $payload['nbf'] > time()) {
        //     return false;
        // }
        $prifix = $payload['role'] ?? '';
        $key    = KeysUtil::getMemberInfoTokenKey($payload['id'], $prifix);
        $tk     = \app\common\utils\RedisManager::conn([
            'persistent' => false,
            'select'     => 1,
        ])->get($key);
        if (empty($tk)) {
            return false;
        }
        // var_dump($key, $token == $tk, $token, $tk);exit;
        $env = env('app.env', 'pro');
        if ($env !== 'dev' && $token != $tk) {
            //单点登录
            return false;
        }
        // 在有效期内有活跃的token就延长ttl
        \app\common\utils\RedisManager::conn([
            'persistent' => false,
            'select'     => 1,
        ])->expire($key, RedisCache::ONE_MONTH);
        return $payload;
    }

    /**
     * base64UrlEncode
     * @param string $input 需要编码的字符串
     * @return string
     */
    private static function base64UrlEncode($input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    /**
     * base64UrlEncode
     * @param string $input 需要解码的字符串
     * @return bool|string
     */
    private static function base64UrlDecode($input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $addle = 4 - $remainder;
            $input .= str_repeat('=', $addle);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

    /**
     * 签名
     * @param $input
     * @param string $key
     * @param string $alg 算法方式
     * @return mixed
     */
    private static function signature($input, $key, $alg = 'HS256')
    {
        $alg_config = [
            'HS256' => 'sha256',
        ];
        return self::base64UrlEncode(hash_hmac($alg_config[$alg], $input, $key, true));
    }
}
